package org.vacoor.nothing.ui.trayicon;

import org.vacoor.nothing.common.misc.util.Platform;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 使用伪透明, 解决 Linux 下透明, 改类中 {@link #setImage(java.awt.Image)} 会处理图片
 * {@link #getImage()} 获取的对象将不是传入的 Image 对象
 * <p/>
 * Linux X11 system tray icon transparency bug:
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6453521
 * <p/>
 * User: Vacoor
 */
class FixX11TransparencyTrayIcon extends TrayIcon {
    private static Image x11TaskBarBackground;

    public FixX11TransparencyTrayIcon(Image image) {
        super(image);
    }

    public FixX11TransparencyTrayIcon(Image image, String tooltip) {
        super(image, tooltip);
    }

    public FixX11TransparencyTrayIcon(Image image, String tooltip, PopupMenu popup) {
        super(image, tooltip, popup);
    }

    @Override
    public void setImage(Image image) {
        if (image != null) {
            image = prepareTrayImage(image);
        }
        super.setImage(image);
    }


    private static Image prepareTrayImage(Image image) {
        SystemTray sysTray = SystemTray.getSystemTray();
        Dimension traySize = sysTray.getTrayIconSize();

        if (!Platform.isX11() || image == null) {
            return image;
        }

        /*-
         * Linux X11 system tray icon transparency bug:
         * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6453521
         */
        BufferedImage img = new BufferedImage(traySize.width, traySize.height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();

        // 创建底色, 用于伪透明
        try {
            if (x11TaskBarBackground == null) {
                // very need cache
                Robot robot = new Robot();
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                // Toolkit.getDefaultToolkit().getScreenInsets()// 1.6 无法获取 Ubuntu 顶部菜单
                int y = 0; // TODO 默认任务栏在顶部, 应该为任务栏y + ( ( 任务栏高度 - 托盘图标高度 ) / 2 ) 稍后处理

                // 获取一个像素宽的任务栏图片
                BufferedImage bg = robot.createScreenCapture(new Rectangle(screenSize.width - 2, y, 1, traySize.height));
                x11TaskBarBackground = bg.getScaledInstance(traySize.width, traySize.height, Image.SCALE_SMOOTH);
            }
            g2d.drawImage(x11TaskBarBackground, 0, 0, null);
        } catch (AWTException ignore) {
        }

        // 获取到的 traySize 总是24
        g2d.drawImage(image, 0, 4, traySize.width, traySize.height - 8, null);
        g2d.dispose();
        return img;
    }
}
